$(function() {
//Declare variable
var  Code= $( "#Code" ),
	Branch=$("#Branch"),
	Productlist = $( "#productlist" ),
	Amount = $( "#Amount" ),	
		allFields = $( [] ).add( Code )
					.add(Amount)
					.add(Productlist),
			tips = $( ".validateTips" ),
			button_name="",
			url="a_order.php", 
			ID="",
			AddTitle="Create Order Product",	
			EditTitle="Update Order Product",	
			rowSelect="",
			row_sub_table_cnt=0,
			no=0,
			o_list={};
			
		//Show Loading
		//showLoader();
		
		Amount.keypress(function(e){
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
				return false;
			}
		});
		//*********************
		// Load data to combobox 
		//********************
		//get json group
		$.get(url, {"c":"b"},function(data){
			//alert(data);
			var obj=eval('('+data+')');
			if (obj!=null){
				$.each(obj, function(index, text) {
					$("#cboBranchName,#Branch").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
		
		$("#cboBranchName").append($('<option></option>').val(0).html('All'));

		$("#cboBranchName").combobox();
		$('.ui-autocomplete-input').css('width', '200px');
		
		
		$.get(url, {"c":"p"},function(data){
			//alert(data);
			var obj=eval('('+data+')');
			if (obj!=null){
				$.each(obj, function(index, text) {
					$("#productlist").append(
						$('<option></option>').val(text).html(index)
					 );
				});
			}
		});	
		
		Productlist.combobox({
			selected: function(event, ui) {
				 var pid=Productlist.val() ;
				 	$.ajax({
						type: 'POST',
						cache: false,
						url: url,
						data: {'m':'HoAmt' ,'p':pid},
						success: function(data){
							$("#remainAmt").attr('innerHTML',data);
						}
					});
			}
		});
	
		$("#btnAddProduct").button({
			icons:{
			 primary: "ui-icon-circle-plus"
			}
		});	
		
		//Load First page
		LoadData(1,true);
		
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='9' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};	
		
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

	function CommaFormatted(amount)
	{
	 
		var delimiter = ","; // replace comma if desired
		var a = amount.split('.',2)
		var d = a[1];
		var i = parseInt(a[0]);
		if(isNaN(i)) { return ''; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		if(n.length > 0) { a.unshift(n); }
		n = a.join(delimiter);
		if(d.length < 1) { amount = n; }
		else { amount = n + '.' + d; }
		amount = minus + amount;
		return amount;
	}

		function getData(id){

			var dataSet={'id':id,'m':'detail'};  
			//alert(id);
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					var obj=eval('('+data+')');
					var m=eval('('+obj['header']+')');
					//clear();
					o_list={};

					//Set No. rows
					row_sub_table_cnt = obj['rows'];
					$("#iCount").attr('innerHTML',row_sub_table_cnt);
					
					Code.val(m['OrderNo']);
					Branch.val(m['Branch']);
					
					$( "#tbNewProduct tbody:first" ).append(obj['html']);
					
					$( "#tbNewProduct tbody tr").each(function(){
							// Return Product id 
							var pid = $(this).find("td").eq(0).html();    
							// Return amount
							var amt = $(this).find("td").eq(3).html();
							// Return Type
	
							o_list[pid]=amt ;
					});
				}
			});
		}
		
		function callAjax(obj,id){
			var m=$("#mode").val();
			//alert($("#mode").val());
			var iRows=0;
			if (m =='edit'){
				iRows=no;
			}else 
				iRows=$("#rowCount").attr('innerHTML');
			
			//alert(iRows);
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id,"rows":iRows},
				success: function(data){
					//alert(data);
					if (m=='add'){
					
						var rows=$("#rowCount").attr('innerHTML');
						
						if (rows=="0"){
							$( "#resultData tbody tr").remove();
						}
						//Insert data to first row.
						$( "#resultData tbody:first" ).prepend( data ); 
						//Set font color
						$( "#resultData tbody tr:first" ).css('color','blue');
						//Plus row number ;
						
						$("#rowCount").attr('innerHTML',parseInt(rows,10)+1);
						
					}else if (m=='edit'){
						rowSelect.html(data);
					}
				
				}
			});
		}
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:true,
			height: 600,
			zIndex:9999,
			width: 750,
			modal: true,
			open: function() { 
				//if ($("#mode" ).val() =="edit"){
					//getData(ID);
				//}else{
				$("#iCount").attr('innerHTML',0);
				row_sub_table_cnt=0;
				$( "#tbNewProduct tbody tr" ).remove();
				allFields.val( "" );
				//}
			},
			close: function() {
				allFields.attr("readonly","");
				$("#iCount").attr('innerHTML',0);
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function setData(){
			var o = {};
			o['OrderNo']=Code.val();
			//o['Branch']=$("#Branch").val();
			o['Amount']=$("#iCount").attr('innerHTML');
			o['Detail']=o_list;
			return o;
		}
		// Check input data in control
		function checkRequireControl(type){
			var bValid=true;
			if (type=='create'){
				bValid = bValid && checkInputFile( Code, "Return Code",1);
				if (countArray(o_list) ==0){
					updateTips( "Please selected project" );
					bValid = false;
				}
			}else {//add
				bValid = bValid && checkInputFile( Amount, "Amount",1);
			}
			return bValid;
		}
		function countArray(obj) {
		  var prop;
		  var propCount = 0;

		  for (prop in obj) {
			propCount++;
		  }
		  return propCount;
		}

		//Add product to list 
		$("#btnAddProduct").live('click',function(){
			// Check input require field 
			if (checkRequireControl('add')){
				if ($("#productlist").attr('selectedIndex') > -1){
					var dataSet={};
					if (o_list[$("#productlist").val()]) {
							alert($("#productlist option:selected").text()+ ' already exist!!');
							return;
					}else if  ( parseInt($("#Amount").val()) >= parseInt( $("#remainAmt").attr('innerHTML') ) ){
							alert('Input Order Amount more than Remain Amount');
							$("#Amount").focus();
							return;
					}else {
							// add product to array
							var list= $("#Amount").val();
							//alert(list);
							o_list[$("#productlist").val()]=list;
					}
					dataSet={"m":"p_detail",
							"id":Productlist.val(),
							"amt":Amount.val()
							};	
					$.post(url,dataSet,function(data){
						row_sub_table_cnt++;
											
						$("#iCount").attr('innerHTML',row_sub_table_cnt);
						 
						if (data != "")
							$( "#tbNewProduct tbody:first" ).prepend(data);
	
						Amount.val('');
					})
				}else
					alert('Please select Product');
			}
			return false;	
		});
		
		$("#btnRemove").live('click',function(){
			var iID=0;
			rowSelect = $(this).parent().parent();
			iID=rowSelect.find("td").eq(0).html();
		
			// Remove data
			delete o_list[iID];
			row_sub_table_cnt--;
			$("#iCount").attr('innerHTML',row_sub_table_cnt);
			rowSelect.remove();
			
			return false;	
		});
		// $(".btnReceive").live('click',function(){
			// ID=$(this).parent().parent().find("td").eq(1).html();
			// $("#type").val('c');
			// $('#Act').submit();
		// });
		
		//Check order -> HO
		$(".btnCheck").live('click',function(){
			ID=$(this).parent().parent().find("td").eq(1).html();
			$("#type").val('c');
			$('#Act').submit();
		});
		//Send -> Branch
		$(".btnSend").live('click',function(){
			ID=$(this).parent().parent().find("td").eq(1).html();
			$("#type").val('d');
			$('#Act').submit();
		});
		//View
		
		$(".btnViewConfirm").live('click',function(){
			ID=$(this).parent().parent().find("td").eq(1).html();
			$("#type").val('vc');
			$('#Act').submit();
		});
		
		$(".btnClose").live('click',function(){
				ID=$(this).parent().parent().find("td").eq(1).html();
				$("#type").val('cl');
				$('#Act').submit();
		});
		$(".btnView").live('click',function(){
				ID=$(this).parent().parent().find("td").eq(1).html();
				$("#type").val('v');
				$('#Act').submit();
		});
		$(".btnViewClose").live('click',function(){
				ID=$(this).parent().parent().find("td").eq(1).html();
				$("#type").val('vcl');
				$('#Act').submit();
		});
		
		//Submit form
		$('#Act').submit(function() { 
			$("#reID").val(ID);
		}); 
		//Add Button
		$( "#btnAdd" ).live('click',function() {
				//Clear data
				o_list={};
				
				$.post(url,{'m':'running'},function(data){
					//alert(data);
					Code.val(data);
				});
				//set mode
				$("#mode").val("add");
				//set title
				$("#dialog-form").dialog({'title':AddTitle});
				$( "#dialog-form" ).dialog( "open" );
				$( "#dialog-form" ).dialog( "option","buttons",{
					"Create":function(){
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl('create') ) {
							callAjax(setData(),0); // call ajax function for add new data
							$( this ).dialog( "close" );
						}
					},
					"Cancel":function(){$( this ).dialog( "close" );}
				});
				return false;	
			});
		// Edit Data
		$(".btnEdit").live('click',function() {
				$("#mode").val("edit"),
				rowSelect=$(this).parent().parent(),
				 
				ID=$(this).parent().parent().find("td").eq(1).html();
				no=$(this).parent().parent().find("td").eq(0).html();
				//alert(no);
				getData(ID),
				$("#dialog-form").dialog({'title':EditTitle});
				$("#dialog-form").dialog("open");
				$("#dialog-form").dialog( "option","buttons",{
					"Update":function(){
						var bValid = true;
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl('create') ) {
							callAjax(setData(),ID); // call ajax for update 
							$( this ).dialog( "close" );
						}
					}
					,"Cancel":function(){
						$( this ).dialog( "close" );
					}
				});
				return false;	
			});
		$(".btnDel").live('click',function(){
				rowSelect = $(this).parent().parent();
				ID=$(this).parent().parent().find("td").eq(1).html();
				$("#mode").val("del");
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						callAjax({"id":ID},0); 	//Call Ajax delete data
						rowSelect.remove(); // remove row
						//Remove number
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						
						
						$( this ).dialog( "close" );
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
			});
		 
		$("#btnSearch").click(function(){
			LoadData(1,true);
 			
		});
		
	function LoadData(page,b){
		$( "#resultData tbody tr" ).remove();
		//Show loading
		showLoader();
		//set criteria
		var dataSet={'m':'search'
					,'code':$("#txtOrderNo").val()
					,'branchid':$("#cboBranchName").val()
					,'datefrom':$("#txtDateFrom").val()
					,'dateto':$("#txtDateTo").val()
					,'status':$("#cboStatus").val()						
					,'page':page
					};
		 //Post 		
		 $.post(url,  dataSet , function(data){
			//alert(data);
			var obj=eval("(" + data + ")");
			//hide loading
			hideLoader();
			
			//set data to table
			$( "#resultData tbody" ).append(obj['data']);
			//set row 
			$("#rowCount").attr('innerHTML',obj['rows']);
			//set page
			if (b){
				var p="<ul>";
				for (var i=parseInt(obj['totalpage']);i >0 ;i--){
					p = p +'<li id="'+i+'">'+i+'</li>';
				}
				p = p+"</ul>";
				$("#paging_button ul").remove();
				$("#paging_button").append(p);
				 
			}
			$("#"+page).css({'background-color' : '#006699'});
		 });
	}
 
			
	$("#paging_button li").live('click',function(){
		$("#paging_button li").css({'background-color' : ''});
 		LoadData(this.id,false);

	});		
		
});
	(function( $ ) {
		$.widget( "ui.combobox", {
		_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
								select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );
					input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			},

			destroy: function() {
				this.input.remove();
				this.button.remove();
				this.element.show();
				$.Widget.prototype.destroy.call( this );
			}
		});
})( jQuery );
	